package com.ht.api.service;

import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import com.ht.api.db.Db;
import com.ht.api.db.Entity;
import com.ht.api.db.StreamLoadConfig;
import com.ht.api.db.util.HtUtil;
import com.ht.api.util.NoticeUtil;
import com.ht.api.util.RuleSqlUtil;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;

/**
 * 人群相关service
 * @author asq
 * @createTime 2025年3月19日 11:59:20
 */
public class AudienceService {

	/**
     * 刷新人群用户
     * @param ds
     * @param config
     * @param audience
     */
    public static void refreshAudience (DataSource ds, StreamLoadConfig config, Entity audience) {
        JSONObject rules = audience.getJSONObject("rules");
        List<Object> params = new ArrayList<>();
        String conditionSql = RuleSqlUtil.buildConditionSql(rules, params);

        // 根据规则sql，创建查询人群变化的对象的sql
        StringBuilder sql = StrUtil.builder();
        sql.append("select bitmap_to_string(bitmap_not(rids.id, normalids.id)) as inids, bitmap_to_string(bitmap_not(normalids.id, rids.id)) as outids ");
        sql.append("from ");
        sql.append("(").append(conditionSql).append(") rids, ");
        sql.append("(select bitmap_union(to_bitmap(oneid)) id from audience_relation where status = 0 and audience_id = ? ) normalids ");
        params.add(audience.getMainId());

        Entity tagUsers = Db.findOne(ds, sql.toString(), params);

        String inids = tagUsers.getStr("inids"); // 新的满足标签的对象
        String outids = tagUsers.getStr("outids"); // 当前需要退出正常标签状态的对象

        List<Entity> datalist = new ArrayList<>();
        String eventTime = DateUtil.now();

        // 处理新满足人群的用户
        if (StrUtil.isNotBlank(inids)) {
            for (String id : inids.split(",")) {
                Entity audienceRelationLogs = Entity.create("audience_relation_logs");
                audienceRelationLogs.set("oneid", id);
                audienceRelationLogs.set("audience_id", audience.getMainId());
                audienceRelationLogs.set("status", 0);
                audienceRelationLogs.set("time", eventTime);

                datalist.add(audienceRelationLogs);
            }
        }

        // 处理不满足人群的用户
        if (StrUtil.isNotBlank(outids)) {
            for (String id : outids.split(",")) {
                Entity audienceRelationLogs = Entity.create("audience_relation_logs");
                audienceRelationLogs.set("oneid", id);
                audienceRelationLogs.set("audience_id", audience.getMainId());
                audienceRelationLogs.set("status", -1);
                audienceRelationLogs.set("time", eventTime);

                datalist.add(audienceRelationLogs);
            }
        }

        Db.insertBatchWithStream(config, datalist);

        if (datalist.size() > 0) {//保存日志
            HtUtil.createLog(ds, audience.getMainId(), StrUtil.format("人群刷新数据：新增客户数-> %s，退出客户数-> %s",
                    StrUtil.isBlank(inids) ? 0 : inids.split(",").length, StrUtil.isBlank(outids) ? 0 : outids.split(",").length));
        }
    }
}
